<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="户号" prop="userId">
        <el-input v-model="queryParams.userId" placeholder="请输入户号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="户号" prop="userId">
        <el-select v-model="queryParams.userId" placeholder="请选择户号" clearable filterable style="width: 100%"
          @change="handleQuery">
          <el-option v-for="item in waterUserOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="表号" prop="meterNo">
        <el-input v-model="queryParams.meterNo" placeholder="请输入表号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="表号" prop="meterNo">
        <el-select v-model="queryParams.meterNo" placeholder="请选择表号" clearable filterable style="width: 100%"
          @change="handleQuery">
          <el-option v-for="item in meterOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="工单编号" prop="orderNumber">
        <el-input v-model="queryParams.orderNumber" placeholder="请输入工单编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="工单编号" prop="orderNumber">
        <el-select v-model="queryParams.orderNumber" placeholder="请选择工单编号" clearable filterable style="width: 100%"
          @change="handleQuery">
          <el-option v-for="item in workOrderOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="维修人员" prop="repairUserId">
        <el-input v-model="queryParams.repairUserId" placeholder="请输入维修人员" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item> -->
      <el-form-item label="维修人员" prop="repairUserId">
        <el-select v-model="queryParams.repairUserId" placeholder="请选择维修人员" clearable filterable style="width: 100%"
          @change="handleQuery">
          <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="维修日期" prop="repairDate">
        <el-date-picker clearable v-model="queryParams.repairDate" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择维修日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="维修状态" prop="repairState">
        <el-select v-model="queryParams.repairState" placeholder="请选择维修状态" clearable>
          <el-option v-for="dict in dict.type.repair_state" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['installation:repairInfo:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['installation:repairInfo:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['installation:repairInfo:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['installation:repairInfo:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="repairInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="id" align="center" prop="id"/>-->
      <el-table-column label="户号" align="center" prop="userId" />
      <el-table-column label="表号" align="center" prop="meterNo" />
      <el-table-column label="工单编号" align="center" prop="orderNumber" />
      <!-- <el-table-column label="维修人员" align="center" prop="repairUserId" /> -->
      <el-table-column label="维修人员" align="center" prop="repairUserId" :formatter="formatUser" />
      <el-table-column label="下发日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修日期" align="center" prop="repairDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.repairDate, '{y}-{m}-{d} {h}:{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="维修状态" align="center" prop="repairState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.repair_state" :value="scope.row.repairState" />
        </template>
      </el-table-column>

      <el-table-column label="维修图片" align="center" prop="pic" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.pic" :width="50" :height="50" />
        </template>
      </el-table-column>

      <el-table-column label="维修描述" align="center" prop="repairMore" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['installation:repairInfo:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['installation:repairInfo:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改表具维修对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="户号" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择户号" clearable filterable style="width: 100%">
            <el-option v-for="item in waterUserOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="表号" prop="meterNo">
          <el-select v-model="form.meterNo" placeholder="请选择表号" clearable filterable style="width: 100%">
            <el-option v-for="item in meterOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="工单编号" prop="orderNumber">
          <el-select v-model="form.orderNumber" placeholder="请选择工单编号" clearable filterable style="width: 100%">
            <el-option v-for="item in workOrderOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="维修人员" prop="repairUserId">
          <el-input v-model="form.repairUserId" placeholder="请输入维修人员" />
        </el-form-item> -->
        <el-form-item label="维修人员" prop="repairUserId">
          <el-select v-model="form.repairUserId" placeholder="请选择维修人员" clearable filterable style="width: 100%">
            <el-option v-for="item in userOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="公司编号" prop="companyId">
          <el-input v-model="form.companyId" placeholder="请输入公司编号" />
        </el-form-item>
        <el-form-item label="公司名称" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名称" />
        </el-form-item> -->

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="维修日期" prop="repairDate">
          <el-date-picker clearable v-model="form.repairDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择维修日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="维修状态" prop="repairState">
          <el-select v-model="form.repairState" placeholder="请选择维修状态">
            <el-option v-for="dict in dict.type.repair_state" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维修描述" prop="repairMore">
          <el-input v-model="form.repairMore" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <!-- <el-form-item label="维修图片" prop="pic">
          <image-upload v-model="form.pic" />
        </el-form-item> -->


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listRepairInfo, getRepairInfo, delRepairInfo, addRepairInfo, updateRepairInfo } from "@/api/installation/repairInfo";
  import { listWorkOrder } from "@/api/service/workOrder";
  import { listUser } from "@/api/system/user";
  import { listWaterUser } from "@/api/installation/waterUser";
  import { listWaterMeter } from "@/api/installation/waterMeter";

  export default {
    name: "RepairInfo",
    dicts: ['repair_state'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表具维修表格数据
        repairInfoList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          userId: null,
          meterNo: null,
          orderNumber: null,
          repairUserId: null,
          repairDate: null,
          repairState: null,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          orderNumber: [
            { required: true, message: "工单编号不能为空", trigger: "blur" }
          ],
          meterNo: [
            { required: true, message: "表号不能为空", trigger: "blur" }
          ],
          userId: [
            { required: true, message: "户号不能为空", trigger: "blur" }
          ],
        },
        // 存储工单选项
        workOrderOptions: [],
        // 存储施工人员选项
        userOptions: [],
        //施工人员查询条件
        userQueryParams: {
          pageNum: 1,
          pageSize: 500,
          isWork: 1
        },
        queryParamsAll: {
          pageNum: 1,
          pageSize: 500
        },
        // 存储用户选项
        waterUserOptions: [],
        // 存储表选项
        meterOptions: [],
        picList: [],
      };
    },
    created() {
      this.getList();
      this.getWorkOrderList();
      this.getUserList();
      this.getWaterMeterList();
      this.getWaterUserList();
    },
    methods: {
      /** 查询表具维修列表 */
      getList() {
        this.loading = true;
        listRepairInfo(this.queryParams).then(response => {
          this.repairInfoList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询工单列表 */
      getWorkOrderList() {
        listWorkOrder(this.queryParamsAll).then(response => {
          this.workOrderOptions = response.rows.map(item => ({
            value: item.orderNumber,
            label: item.orderNumber
          }));
        });
      },
      /** 查询施工人员列表 */
      getUserList() {
        listUser(this.userQueryParams).then(response => {
          this.userOptions = response.rows.map(item => ({
            value: item.userId,
            label: item.userName
          }));
        });
      },
      /** 查询表具列表 */
      getWaterMeterList() {
        listWaterMeter(this.queryParamsAll).then(response => {
          this.meterOptions = response.rows.map(item => ({
            value: item.meterNo,
            label: item.meterNo
          }));
        });
      },
      /** 查询用户列表 */
      getWaterUserList() {
        listWaterUser(this.queryParamsAll).then(response => {
          this.waterUserOptions = response.rows.map(item => ({
            value: item.userId,
            label: item.userId
          }));
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          userId: null,
          meterNo: null,
          orderNumber: null,
          repairUserId: null,
          companyId: null,
          companyName: null,
          repairDate: null,
          repairState: null,
          pic: null,
          repairMore: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
        this.picList = []; // 重置图片列表
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加表具维修";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getRepairInfo(id).then(response => {
          this.form = response.data;

          // 新增：处理图片数据
          if (this.form.pic) {
            // 将逗号分隔的图片字符串转换为数组
            this.picList = this.form.pic.split(',');
          } else {
            this.picList = [];
          }


          this.open = true;
          this.title = "修改表具维修";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateRepairInfo(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addRepairInfo(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除表具维修编号为"' + ids + '"的数据项？').then(function () {
          return delRepairInfo(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('installation/repairInfo/export', {
          ...this.queryParams
        }, `repairInfo_${new Date().getTime()}.xlsx`)
      },
      formatUser(row, column, cellValue) {
        // if (cellValue == null) return '未分配';
        // 统一转为字符串比较
        const user = this.userOptions.find(item =>
          String(item.value) === String(cellValue)
        );
        return user.label;
      }
    }
  };
</script>